// pages/scoreResult/scoreResult.js
const { getExamResult, getFinishCourse, getAllPoster} = require('../../api/geData.js')
const util = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    className:'',
    courseName:'',
    attendScore:'',
    taskScore:'',
    midtermScore:'',
    terminalScore:'',
    timer:'',
    homework:'',
    midTest:'',
    finTest:'',
    totalScore: '',
    noScore: true,
    customWish:'',
    teacherWish:'',
    realName:'',
    classBegin:'',
    classEnd:'',
    showResultcourse:false,
    index:0,
    posterBg:[],
    posterScore:'',
    posterData:{},
    saveSuccessDialog:false,
    saveErrorDialog:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.stuId == 'undefined' || options.formalclassid =='undefined')
    {
      this.setData({
        noScore:false
      })
    }else{
      getExamResult(options.stuId, options.formalclassid).then(res => {
        if (res.status === 'success') {
          let totalScore = (res.examineScore.attendScore * res.assessment.timer + res.examineScore.taskScore * res.assessment.homework + res.examineScore.midtermScore * res.assessment.midTest + res.examineScore.terminalScore * res.assessment.finTest) / 100;
          this.setData({
            noScore: true,
            className: res.assessment.className,
            attendScore: res.examineScore.attendScore,
            taskScore: res.examineScore.taskScore,
            midtermScore: res.examineScore.midtermScore,
            terminalScore: res.examineScore.terminalScore,
            customWish: res.examineScore.customWish,
            teacherWish: res.examineScore.teacherWish,
            timer: res.assessment.timer,
            homework: res.assessment.homework,
            midTest: res.assessment.midTest,
            finTest: res.assessment.finTest,
            totalScore: totalScore,
            realName:res.realName,
            classBegin:res.formalClass.classBegin,
            classEnd:res.formalClass.classEnd,
            courseName:res.formalClass.courseName
          })
        } else {
          this.setData({
            noScore: false
          })
        }
      })
    }
    //获取海报图
    getAllPoster(0).then(res => {
      this.setData({
        posterBg: res.list
      })
      getFinishCourse(options.hcId).then(res => {
        this.setData({
          posterScore: res.score,
          posterData: res.map
        })
        this.createPosterPic()
      })
    })
  },
  // 生成海报
  createPosterPic()
  {
    let that=this
    let posterData = that.data.posterData
    let posterScore = that.data.posterScore
    // console.log(that.data.posterBg[that.data.index])
    // console.log(that.data.posterBg[that.data.index].imgUrl)
    let promise1 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: that.data.posterBg[that.data.index].imgUrl,
        success: function (res) {
          resolve(res);
        }
      })
    });
    let promise2 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: that.data.posterData.photo,
        success: function (res) {
          resolve(res);
        }
      })
    });

    let promise3 = new Promise(function (resolve, reject) {
      wx.getImageInfo({
        src: '/images/grade/college.jpg',
        success: function (res) {
          resolve(res);
        }
      })
    });

    Promise.all([
      promise1, promise2, promise3
    ]).then(res => {
      const ctx = wx.createCanvasContext('shareImg')
      //主要就是计算好各个图文的位置
      ctx.drawImage(res[0].path, 0, 0, 337, 482.5)
      ctx.save()
      ctx.beginPath()
      ctx.arc(67.25, 60.75, 19.75, 0, 2 * Math.PI)
      ctx.setStrokeStyle('red')
      ctx.stroke()
      ctx.clip()
      if (res[1].path.indexOf('wxfile') != -1 || res[1].path.indexOf('http') != -1) {
        ctx.drawImage(res[1].path, 47.5, 41, 39.5, 39.5)
      } else {
        ctx.drawImage('/' + res[1].path, 47.5, 41, 39.5, 39.5)
      }
      ctx.restore()

      ctx.drawImage('/' + res[2].path, 210, 333, 77, 77)

      ctx.setTextAlign('center')
      ctx.setFillStyle('#FF6252')
      ctx.setFontSize(15)
      ctx.fillText(posterData.realName, 127.5, 54.5)
      ctx.fillText('恭喜您顺利结课！', 222.5, 54.5)
      ctx.fillText('《' +posterData.courseName + '》', 177.5, 74.5)


      ctx.setTextAlign('center')
      ctx.setFillStyle('#FF6252')
      ctx.setFontSize(24)
      // 下面这三行是图片中的文字，这些文字也是要通过canvas画上去的
      ctx.fillText(posterData.number, 67.5, 352)
      ctx.fillText(posterScore, 136.5, 352)
      ctx.fillText(util.formatTime(posterData.closeTime, 1).split(' ')[0], 105, 405)

      ctx.setTextAlign('center')
      ctx.setFillStyle('#666666')
      ctx.setFontSize(10)
      ctx.fillText('打卡次数', 67.5, 366.5)
      ctx.fillText('结课成绩', 136.5, 366.5)
      ctx.fillText('结课时间', 105, 424.5)

      ctx.setTextAlign('left')
      ctx.setFillStyle('#FF6252')
      ctx.setFontSize(10)
      ctx.fillText('扫码关注国科学院~', 210, 424.5)
      ctx.stroke()
      ctx.draw()
    })
  },
  toggleDialog() {
    this.setData({
      showResultcourse: !this.data.showResultcourse
    })
  },
  changeBg()
  {
    let posterBgLen = this.data.posterBg.length
    if (this.data.index < posterBgLen-1)
    {
      this.data.index++
      this.setData({
        showResultcourse: true,
        index: this.data.index
      })
      this.createPosterPic()
    }else{
      this.setData({
        showResultcourse: true,
        index: 0
      })
      this.createPosterPic()
    }
  },
  /**
   * 保存到相册
  */
  save: function () {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    // 生产环境时 记得这里要加入获取相册授权的代码
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序相册功能，后续调用 wx.saveImageToPhotosAlbum 接口不会弹窗询问
              wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 337,
                height: 482.5,
                destWidth: 674,
                destHeight: 965,
                canvasId: 'shareImg',
                success: function (res) {
                  that.setData({
                    preurl: res.tempFilePath,
                    previewHidden: false,
                  })
                  that.startSaveImage()
                  wx.hideLoading()
                },
                fail: function (res) {
                  that.setData({
                    saveErrorDialog: true
                  })
                  setTimeout(() => {
                    that.setData({
                      saveErrorDialog: false
                    })
                  }, 2000)
                }
              })
            }
          })
        } else {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 337,
            height: 482.5,
            destWidth: 674,
            destHeight: 965,
            canvasId: 'shareImg',
            success: function (res) {
              that.setData({
                preurl: res.tempFilePath,
                previewHidden: false,
              })
              that.startSaveImage()
              wx.hideLoading()
            },
            fail: function (res) {
              that.setData({
                saveErrorDialog: true
              })
              setTimeout(() => {
                that.setData({
                  saveErrorDialog: false
                })
              }, 2000)
            }
          })
        }
      }
    })

  },

  startSaveImage: function () {
    let that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.preurl,
      success(res) {
        that.setData({
          previewHidden: true,
          saveSuccessDialog: true
        })
        setTimeout(() => {
          that.setData({
            saveSuccessDialog: false
          })
        }, 2000)
        // wx.showModal({
        //   content: '图片已保存到相册，赶紧晒一下吧~',
        //   showCancel: false,
        //   confirmText: '好哒',
        //   confirmColor: '#72B9C3',
        //   success: function (res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定');
        //       that.setData({
        //         previewHidden: true
        //       })
        //     }
        //   }
        // })
      },fail()
      {
        that.setData({
          saveErrorDialog: true
        })
        setTimeout(() => {
          that.setData({
            saveErrorDialog: false
          })
        }, 2000)
      }
    })
  },
})